<?php

namespace backend\modules\qywx\controllers;

use common\business\CommonHelper;
use common\business\qywx\QywxUserApiHandler;
use common\business\QywxUserService;
use common\business\task\TaskService;
use common\consts\Consts;
use common\models\Department;
use common\result\ActionResult;
use Yii;
use common\models\qywx\QywxUser;
use common\models\qywx\QywxUserSearch;
use yii\helpers\Json;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * QywxUserController implements the CRUD actions for QywxUser model.
 */
class QywxUserController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                    'batch-delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all QywxUser models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new QywxUserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single QywxUser model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new QywxUser model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new QywxUser();

        if (!$model->load(Yii::$app->request->post())) {
            return $this->render('create', [
                'model' => $model,
            ]);
        }

        $result = (new QywxUserService())->create($model);
        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success', Yii::t('app', $result->message));
            return $this->redirect(['view', 'id' => $model->qywx_user_id]);
        }

        Yii::$app->getSession()->setFlash('error', Yii::t('app', $result->message));
        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing QywxUser model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if (!$model->load(Yii::$app->request->post())) {
            return $this->render('update', [
                'model' => $model,
            ]);
        }

        $result = (new QywxUserService())->update($model);
        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success', Yii::t('app', $result->message));
            return $this->redirect(['view', 'id' => $model->qywx_user_id]);
        }

        Yii::$app->getSession()->setFlash('error', Yii::t('app', $result->message));
        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing QywxUser model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
//        $result = (new QywxUserService())->delete($model);
        $result = (new QywxUserApiHandler())->deleteQywxUser($model);
        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success', $result->message);
            return $this->redirect(['index']);
        }
        Yii::$app->getSession()->setFlash('error', $result->message);
        return $this->redirect(['view', 'id' => $model->id]);
    }


    /**
     * @param $ids4Delete string
     * @return string
     */
    public function actionBatchDelete(){
        $params = Yii::$app->request->post();
        $idsArr = explode(',', $params['ids4Delete']);

        $idListArr = [];
        foreach ($idsArr as $id){
            $user = QywxUser::findOne([
                'id' => $id,
            ]);
            array_push($idListArr, $user->id);
        }

        $result = (new QywxUserApiHandler())->batchDeleteQywxUser($idListArr);
        return $result->toJson();
    }

    /**
     * Finds the QywxUser model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return QywxUser the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = QywxUser::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionSyncByDepartment($department_id){
        $departmentInDb = Department::findOne($department_id);
//        $requestData = ['department_wx_id' => $departmentInDb->qywx_id];
        $requestData = ['department_number' => $departmentInDb->number];
        $result = (new TaskService())->createTask(Consts::TASK_TYPE_EMPLOYEE_TO_QYWX, 'qywx', Consts::NO, Json::encode($requestData));
        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success',  $result->message);
            return $this->redirect(['/task/index']);
        }
        else {
            Yii::$app->getSession()->setFlash('error', $result->getMessage());
            return $this->redirect(['index']);
        }
    }
}
